import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { showLoading, hideLoading } from '@/utils/loading'
import LOG from './log'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    showLoading()
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    hideLoading()
    LOG.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    hideLoading()
    const res = response.data
    const http_status_code = response.status
    const resStr = JSON.stringify(res)
    const resJson = JSON.parse(resStr)
    LOG.log(http_status_code)
    // LOG.log('请求数据http_status_code： ' + http_status_code)
    if (http_status_code === 203) {
      // to re-login
      MessageBox.confirm('登陆已过期，请重新登录', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
      return Promise.reject(new Error('Error'))
    }
    // if the custom code is not 20000, it is judged as an error.
    if (resJson.status !== 200) {
      Message({
        message: resJson.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return resJson
    }
  },
  error => {
    hideLoading()
    LOG.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
